package com.gzkemays.music.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzkemays.common.FileType;
import com.gzkemays.entity.AliOssConfig;
import com.gzkemays.music.expcetion.MusicException;
import com.gzkemays.music.mapper.MusicMapper;
import com.gzkemays.music.po.Music;
import com.gzkemays.music.po.vo.MusicBasicInformationVo;
import com.gzkemays.music.service.MusicService;
import com.gzkemays.utils.AliUtils;
import org.apache.ibatis.annotations.Options;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 服务实现类
 *
 * @author gzkemays
 * @since 2021-03-27
 */
@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements MusicService {
  public static final String ACCESS_KEY = "LTAI4G3PhMxNCPCnZWeU7DR9";
  public static final String SECURITY_KEY = "PKZlC3saXqmk97PWMDFCLt6HXresOq";
  public static final String BUCKET = "map-depot";
  public static final String END_POINT = "oss-cn-beijing.aliyuncs.com";
  public static final String SAVE_PATH = "music";
  public static final String URL = "http://img.hwy-study.xyz/";

  @Override
  @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
  public Music upload(MusicBasicInformationVo vo) throws IOException {
    String url;
    if (validate(vo.getFileName())) {
      url =
          URL
              + AliUtils.uploadImgToOSS(
                  AliOssConfig.builder().accessKey(ACCESS_KEY).secretKey(SECURITY_KEY)
                      .bucketName(BUCKET).endPoint(END_POINT).savePath(SAVE_PATH).stream(
                          vo.getFile().getInputStream())
                      .fileName(vo.getFileName())
                      .ext(FileType.PERIOD_MP3)
                      .build());
      Music music = Music.generatorMusic(vo, url);
      baseMapper.insert(music);
      return music;
    }
    throw new MusicException(500, "发生未知错误");
  }

  @Override
  public Music findUrlById(int id) {
    return baseMapper.selectById(id);
  }

  @Override
  public List<Music> findMusicList() {
    return baseMapper.selectList(null);
  }
}
